package cn.bvin.app.voicerecord;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import junit.runner.Version;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaRecorder;
import android.media.MediaRecorder.OnErrorListener;
import android.media.MediaRecorder.OnInfoListener;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.internal.VersionUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {

	private MediaRecorder mr;
	private MediaPlayer mp;
	private File voiceDir;
	private File curVoiveFile;
	private Button btStartRecord,btStopRecord;
	private Button btStartPlay,btStopPlay;
	private ImageView iv;
	private Drawable[] micImages;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		voiceDir = new File(Environment.getExternalStorageDirectory(), "voice");
		if (!voiceDir.exists()) {
			voiceDir.mkdirs();
		}
		initMediaRecorder();
		initMediaPlayer();
		setContentView(R.layout.activity_main);
		btStartRecord = (Button) findViewById(R.id.button1);
		btStopRecord = (Button) findViewById(R.id.button2);
		btStartPlay = (Button) findViewById(R.id.button3);
		btStopPlay = (Button) findViewById(R.id.button4);
		iv = (ImageView) findViewById(R.id.imageView1);
		micImages = new Drawable[] { getResources().getDrawable(R.drawable.record_animate_01),
				getResources().getDrawable(R.drawable.record_animate_02), getResources().getDrawable(R.drawable.record_animate_03),
				getResources().getDrawable(R.drawable.record_animate_04), getResources().getDrawable(R.drawable.record_animate_05),
				getResources().getDrawable(R.drawable.record_animate_06), getResources().getDrawable(R.drawable.record_animate_07),
				getResources().getDrawable(R.drawable.record_animate_08), getResources().getDrawable(R.drawable.record_animate_09),
				getResources().getDrawable(R.drawable.record_animate_10), getResources().getDrawable(R.drawable.record_animate_11),
				getResources().getDrawable(R.drawable.record_animate_12), getResources().getDrawable(R.drawable.record_animate_13),
				getResources().getDrawable(R.drawable.record_animate_14), };
	}
	
	@SuppressLint("InlinedApi")
	private void initMediaRecorder() {
		mr = new MediaRecorder();
		mr.setAudioSource(MediaRecorder.AudioSource.MIC);
		if (VERSION.SDK_INT>10) {
			mr.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
			mr.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
		}else {
			mr.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
			mr.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
		}
		mr.setOnErrorListener(new OnErrorListener() {
			
			@Override
			public void onError(MediaRecorder mr, int what, int extra) {
				SimpleLogger.log_e("MediaRecorder#onError", what+":"+extra);
			}
		});
		mr.setOnInfoListener(new OnInfoListener() {
			
			@Override
			public void onInfo(MediaRecorder mr, int what, int extra) {
				//SimpleLogger.log_e("MediaRecorder#onInfo", what+":"+extra);
			}
		});
		
	}
	
	private void initMediaPlayer() {
		mp = new MediaPlayer();
		mp.setOnCompletionListener(new OnCompletionListener() {
			
			@Override
			public void onCompletion(MediaPlayer mp) {
				btStartPlay.setEnabled(true);
				btStartRecord.setEnabled(true);
				btStopPlay.setEnabled(false);
				btStopRecord.setEnabled(false);
			}
		});
		mp.setOnErrorListener(new MediaPlayer.OnErrorListener() {
			
			@Override
			public boolean onError(MediaPlayer mp, int what, int extra) {
				SimpleLogger.log_e("MediaPlayer#onError", what+":"+extra);
				return false;
			}
		});
		mp.setOnPreparedListener(new OnPreparedListener() {
			
			@Override
			public void onPrepared(MediaPlayer mp) {
				SimpleLogger.log_e("initMediaPlayer", "onPrepared");
				btStartRecord.setEnabled(false);
				btStartPlay.setEnabled(false);
				btStopPlay.setEnabled(false);
				btStopRecord.setEnabled(true);
			}
		});
		mp.setOnInfoListener(new MediaPlayer.OnInfoListener() {
			
			@Override
			public boolean onInfo(MediaPlayer mp, int what, int extra) {
				SimpleLogger.log_e("MediaPlayer#onInfo", what+":"+extra);
				return false;
			}
		});
	}
	
	SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd-hh-mm-ss");
	
	public void startRecord(View v) {
		
		try {
			initMediaRecorder();
			curVoiveFile = File.createTempFile(sdf.format(new Date()), ".arm", voiceDir);
			SimpleLogger.log_e("startRecord-file", curVoiveFile.exists());
			mr.setOutputFile(curVoiveFile.getAbsolutePath());
			mr.prepare();
			mr.start();
			updateMicStatus();
		} catch (IllegalStateException e) {
			e.printStackTrace();
			stopRecord(v);
			initMediaRecorder();
			SimpleLogger.log_e("startRecord", e.getLocalizedMessage());
		} catch (IOException e) {
			e.printStackTrace();
			stopRecord(v);
			initMediaRecorder();
			SimpleLogger.log_e("startRecord", e.getLocalizedMessage());
		}
		
	}
	
	public void stopRecord(View v) {
		mr.stop();
		mr.reset();
		mr.release();
		mr = null;
		btStartRecord.setEnabled(true);
		btStopRecord.setEnabled(false);
		btStartPlay.setEnabled(true);
		btStopPlay.setEnabled(false);
		mHandler.removeCallbacks(mUpdateMicStatusTimer);
	}
	
	public void startPlay(View v) {
		if (curVoiveFile==null||!curVoiveFile.exists()) {
			SimpleLogger.log_e("startPlay", "录音文件不存在");
			return;
		}
		if (mp==null) {
			initMediaPlayer();
		}
		try {
			mp.setDataSource(curVoiveFile.getAbsolutePath());
			mp.prepare();
			mp.start();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
			stopPlay(v);
			SimpleLogger.log_e("startPlay", e);
		} catch (SecurityException e) {
			e.printStackTrace();
			stopPlay(v);
			SimpleLogger.log_e("startPlay", e);
		} catch (IllegalStateException e) {
			e.printStackTrace();
			stopPlay(v);
			SimpleLogger.log_e("startPlay", e);
		} catch (IOException e) {
			e.printStackTrace();
			stopPlay(v);
			SimpleLogger.log_e("startPlay", e);
		}
	}
	
	public void stopPlay(View v) {
		mp.stop();
		mp.reset();
		mp.release();
		mp = null;
	}
	
	private void deleteVoiceDir() {
		File file = new File(Environment.getExternalStorageDirectory(),"voice");
		delFile(file);
	}
	
	//遍历删除文件
	private void delFile(File file) {
		if(file.isDirectory()) {
			for (File f : file.listFiles()) {
				delFile(f);
			}
		}else if (file.isFile()) {
			file.delete();
		} 
	}
	
	private final Handler mHandler = new Handler();  
    private Runnable mUpdateMicStatusTimer = new Runnable() {  
        public void run() {  
            updateMicStatus();  
        }  
    };  
	/** 
     * 更新话筒状态 
     * 
     */  
    private int BASE = 150;  
    private int SPACE = 100;// 间隔取样时间  
    private void updateMicStatus() {  
        if (mr != null) {  
        	int maxAmpl = mr.getMaxAmplitude();
        	int ratio = (int) maxAmpl/BASE;  
            int db = 0;// 分贝  
            if (ratio > 1)  
                db = (int) (20 * Math.log10(ratio));  
            SimpleLogger.log_e(maxAmpl+"分贝值："+db,"第几格："+db / 10);  
            
            iv.setImageDrawable(micImages[db / 7]); 
            mHandler.postDelayed(mUpdateMicStatusTimer, SPACE);  
        }  
    }  
}
